// This is the main DLL file.

#include "stdafx.h"

#include "..\DBComputingService\Common.h"
#include "DBStatusViewerGateway.h"

#pragma comment (lib, "Ws2_32.lib")

namespace DBStatusViewerGateway {

	DBStatus^ Gateway::GetStatus()
	{
		DBStatus^ status = nullptr;

		// start sockets
		WSADATA wsaData;
		int iResult = ::WSAStartup(MAKEWORD(2,2), &wsaData);
		if(iResult != 0)
		{
			return nullptr;
		}

		// create socket
		struct addrinfo *result = NULL;
		struct addrinfo hints;

		ZeroMemory(&hints, sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_protocol = IPPROTO_TCP;

		iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
		if ( iResult != 0 ) {
			goto Exit;
		}

		// create sockect
		SOCKET ConnectSocket = INVALID_SOCKET;
		ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
		if (ConnectSocket == INVALID_SOCKET) {
			goto Exit;
		}


		// Connect to server.
		iResult = connect( ConnectSocket, result->ai_addr, (int)result->ai_addrlen);
		if (iResult == SOCKET_ERROR) {
			closesocket(ConnectSocket);
			goto Exit;
		}

		// send termination message
		char msg[1];
		msg[0] = 'D';
		send(ConnectSocket, msg, 1, 0);

		StatusAnswer answer;
		memset(&answer, 0, sizeof(StatusAnswer));
		if(recv(ConnectSocket, (char*)&answer, sizeof(StatusAnswer), 0) > 0)
		{
			status = gcnew DBStatus();
			status->DBIndex = answer.dbIndex;
			status->DBCount = answer.maxSubDb;
			status->Percent = answer.iPercent;
			status->BuiltDB = gcnew String(answer.sDbName);
			status->ProcessName = gcnew String(answer.sProcessName);
		}

		closesocket(ConnectSocket);

Exit:;
		WSACleanup();

		return status;
	}
}


